package com.snow.fvmusic.aspect;

import com.github.pagehelper.PageInfo;
import com.snow.fvmusic.service.AsynchTaskService;
import com.snow.fvmusic.vo.ArticleVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author ：snow
 * @Date ：Created in 2020-10-26
 * @Description：
 * @Modified By：
 * @Version:
 */
@Aspect
@Slf4j
@Component
@Order(3)
public class StatisticAspect {
    @Resource
    private AsynchTaskService asynchTaskService;
    @AfterReturning(value = "execution(public * com.snow.fvmusic.service.ArticleVOService.getArticlesOfMusicPool(Long,..))"
            + "&&args(poolId, ..)", returning = "ret", argNames = "ret,poolId")
    public void statistic(Object ret, Long poolId){
        log.info("ret======>" + ret);
        log.info("poolId======>" + poolId);
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        if (poolId == null) return;
        log.info("start statistic pool views Thread...");
        asynchTaskService.incrMusicPoolsViews(poolId, request);
        if (ret instanceof PageInfo){
            List<ArticleVO> articles = ((PageInfo<ArticleVO>) ret).getList();
            List<Long> ids = articles.stream().map(ArticleVO::getId).collect(Collectors.toList());
            log.info("start statistic articles views Thread...");
            asynchTaskService.incrArticlesViews(ids, request);

        }
    }
}
